package com.example.writelogdemo.utils

import android.util.Log
import java.io.*

class WriteLogToFileUtil private constructor(){
   companion object {
       private const val VERBOSE = 'v'
       private const val DEBUG = 'd'
       private const val INFO = 'i'
       private const val WARN = 'W'
       private const val ERROR = 'e'
       private var mLogRootPath:String = ""
       private var mFileName:String = ""
       private val TAG: String = WriteLogToFileUtil::class.java.getName()
       val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { WriteLogToFileUtil() }
   }

    private fun LogToFileUtil() {
        // 获得文件储存路径
        mLogRootPath = FileManager.getLogRootPath()
    }


    fun init() {
        val timeStr: String = TimeUtils.parserTimeToYmdHm(System.currentTimeMillis())
        // log日志名，使用时间命名，保证不重复
        mFileName = "$mLogRootPath/log_$timeStr.txt"
        val file = File(mFileName)
        if (!file.exists()) {
            try {
                val isFlag = file.createNewFile()
                Log.e(
                  TAG,
                    "创建文件是否成功 = $isFlag"
                )
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

    fun v(tag: String, msg: String) {
        writeToFile(WriteLogToFileUtil.VERBOSE, tag, msg)
    }

    fun d(tag: String, msg: String) {
        writeToFile(WriteLogToFileUtil.DEBUG, tag, msg)
    }

    fun i(tag: String, msg: String) {
        writeToFile(WriteLogToFileUtil.INFO, tag, msg)
    }

    fun w(tag: String, msg: String) {
        writeToFile(WriteLogToFileUtil.WARN, tag, msg)
    }

    fun e(tag: String, msg: String) {
        writeToFile(WriteLogToFileUtil.ERROR, tag, msg)
    }

    /**
     * 将log信息写入文件中
     */
    private fun writeToFile(type: Char, tag: String, msg: String) {
        val timeStr: String = TimeUtils.parserTimeToYmdHm(System.currentTimeMillis())
        // log日志内容，可以自行定制
        val log = "$timeStr $type $tag $msg\n"
        var fos: FileOutputStream? = null
        var bw: BufferedWriter? = null
        try {
            // 这里的第二个参数代表追加还是覆盖，true为追加，false为覆盖
            fos = FileOutputStream(mFileName, true)
            bw = BufferedWriter(OutputStreamWriter(fos))
            bw.write(log)
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            try {
                // 关闭缓冲流
                bw?.close()
                fos?.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }
}